﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Xml;

namespace LicenserProduction
{
    public partial class LicenseDetails : UserControl
    {
        int m_licenseId;

        public LicenseDetails(LicenserInformation licInfo, int licenseID)
        {
            InitializeComponent();
            licenserInformation = licInfo;
            licensesBindingSource.DataSource = licenserInformation;
            licensesBindingSource.DataMember = "Licenses";
            licensesBindingSource.Filter = "LicenseID = " + licenseID;

            comboBox1.DataSource = licenserInformation.LicenseTypeEnum;
            comboBox1.DisplayMember = "Description";
            comboBox1.ValueMember = "Code";

            comboBox1.SelectedValue = ((DataRowView)licensesBindingSource.Current).Row["LicenseType"];
            comboBox1.SelectedValueChanged += new EventHandler(comboBox1_SelectedValueChanged);

            featureDetails1.Init(licenserInformation, licenseID);
            m_licenseId = licenseID;

        }

        void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            ((DataRowView)licensesBindingSource.Current).Row["LicsenseType"] = comboBox1.SelectedValue;
        }

        internal void btnGenerate_Click(object sender, EventArgs e)
        {
            featuresBindingSource.EndEdit();
            licensesBindingSource.EndEdit();

            LicenserInformation.LicensesRow licRow = (LicenserInformation.LicensesRow)
                ((DataRowView)((licensesBindingSource.Current))).Row;
            string[] ids = ComputerIds;
            foreach (string id in ids)
            {
                saveFileDialog1.FileName = "license_" + licRow.CustomerInfoRow.CustomerName +
                    "_" + licRow.ProductName + "_" + id + ".xml";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    XmlDocument doc = ProduceSingleLicense(id);
                    doc.Save(saveFileDialog1.FileName);
                }
            }
        }

        private XmlDocument ProduceSingleLicense(string computerId)
        {
            LicenserAPI.Logic.LicenseInfo licStruct = new LicenserAPI.Logic.LicenseInfo();
            XmlDocument doc = new XmlDocument();
            LicenserAPI.Logic licenseLogic = new LicenserAPI.Logic();

            LicenserInformation.LicensesRow licRow = 
                (LicenserInformation.LicensesRow)((DataRowView)licensesBindingSource.Current).Row;
            XmlElement elem = doc.CreateElement(licRow.ProductName);
            doc.AppendChild(elem);

            XmlElement child = doc.CreateElement("LicenseType");
            child.InnerText = licRow.LicenseType.ToString();
            elem.AppendChild(child);

            child = doc.CreateElement("ComputerId");
            child.InnerText = computerId;
            elem.AppendChild(child);

            child = doc.CreateElement("Features");
            elem.AppendChild(child);
            elem = child;

            licStruct.computerID = computerId;
            licStruct.kind = (LicenserAPI.Logic.LicenseType)licRow.LicenseType;
            licStruct.passCode = licRow.Passcode;
            ArrayList ar = new ArrayList();

            foreach (DataRowView drv in featureDetails1.Features)
            {
                LicenserAPI.Logic.FeatureInfo featureInfo = new LicenserAPI.Logic.FeatureInfo();
                LicenserInformation.FeaturesRow feature =
                    (LicenserInformation.FeaturesRow)drv.Row;

                featureInfo.featureName = feature.FeatureName;
                if (feature.IsExpirationNull())
                {
                    featureInfo.timeDepend = false;
                }
                else
                {
                    featureInfo.timeDepend = feature.IsTimeDepended;
                }
                if (feature.IsExpirationNull())
                {
                    featureInfo.expiration = System.DateTime.MaxValue;
                }
                else
                {
                    featureInfo.expiration = feature.Expiration;
                }
                ar.Add(featureInfo);

                child = doc.CreateElement("Feature");
                elem.AppendChild(child);
                XmlAttribute attr = doc.CreateAttribute("Name");
                attr.Value = featureInfo.featureName;
                child.Attributes.Append(attr);

                attr = doc.CreateAttribute("IsTimeDepended");
                attr.Value = XmlConvert.ToString(featureInfo.timeDepend);
                child.Attributes.Append(attr);

                if (featureInfo.timeDepend)
                {
                    attr = doc.CreateAttribute("Expiration");
                    attr.Value = XmlConvert.ToString(featureInfo.expiration,XmlDateTimeSerializationMode.Local);
                    child.Attributes.Append(attr);
                }
            }
            licStruct.features = 
                (LicenserAPI.Logic.FeatureInfo[])ar.ToArray(typeof(LicenserAPI.Logic.FeatureInfo));

            elem = doc.CreateElement("Signature");
            doc.DocumentElement.AppendChild(elem);
            LicenserAPI.Logic logic = new LicenserAPI.Logic();
            elem.InnerText = logic.CreateSignature(licStruct);
            return doc;
        }

        private string[] ComputerIds
        {
            get
            {
                ArrayList ids = new ArrayList();
                string compIds = "";

                if ((int)(((DataRowView)licensesBindingSource.Current).Row["LicenseType"]) == 1)
                {
                    compIds = (((DataRowView)licensesBindingSource.Current).Row["ComputerIds"].ToString());
                    StringReader sr = new StringReader(compIds);
                    string compId = sr.ReadLine();
                    while (compId != null)
                    {
                        ids.Add(compId);
                        compId = sr.ReadLine();
                    }
                    sr.Close();
                }
                else
                {
                    ids.Add("");
                }
                return (string [])ids.ToArray(typeof(String));
            }
        }

    }
}
